package com.zjun.threadpool.support.eager;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

public class TaskQueue<R extends Runnable> extends LinkedBlockingQueue<Runnable> {
    private EagerThreadPoolExecutor executor;

    public TaskQueue(int capacity){
        super(capacity);
    }
    public void setExecutor(EagerThreadPoolExecutor executor){
        this.executor = executor;
    }

    @Override
    public boolean offer(Runnable runnable) {
        //获取线程池中的线程数
        int currentPoolThreadSize = executor.getPoolSize();
        if (executor.getSubmittedTaskCount() < currentPoolThreadSize){
            return super.offer(runnable);
        }
        /**
         * 当线程池数量小于最大线程池数，直接返回false,这样线程池就会创建非核心代码
         */
        if (currentPoolThreadSize<executor.getMaximumPoolSize()){
            return false;
        }
        //如果当前线程池大于最大线程，任务加入阻塞队列
        return super.offer(runnable);
    }

    public boolean retryOffer(Runnable command, long timeout, TimeUnit timeUnit) throws InterruptedException {
        if (executor.isShutdown()){
            throw new RejectedExecutionException("Executor is shutdown!");
        }
        return super.offer(command,timeout,timeUnit);
    }
}
